#include <stdio.h>
#include <stdlib.h>

#include <stdio.h>
#include <stdlib.h>

void coutingSort(int *A, int n, int *B, int *C, int k){
	int i;

	//Passo 1
	for(i=0;i<n;i++) C[A[i]-1]++;

	//Passo 2
	for(i=1;i<k;i++) C[i] += C[i-1];

	//Passo 3
	for(i=n-1;i>=0;i--) {
		B[C[A[i]-1]-1] = A[i];
		C[A[i]-1]--;
	}

	//Passo 4
	for(i=0;i<n;i++) A[i] = B[i];
}

/*
int main() {
	int vetA[10] = {1,2,4,6,1,3,3,1,2,6};
	int vetB[10] = {0,0,0,0,0,0,0,0,0,0}, vetC[6] = {0,0,0,0,0,0};
	int i;

	coutingSort(vetA, 10, vetB, vetC, 6);

	for(i=0;i<10;i++) printf("%d ", vetA[i]);

	getch();
	return 0;
}
*/


void Counting_sort(int A[], int k, int n, char nomeArquivo[])
{
	int i, j;
	int B[n], C[n];
	for(i = 0; i <= k; i++)
		C[i] = 0;
	for(j =1; j <= n; j++)
		C[A[j]] = C[A[j]] + 1;
	for(i = 1; i <= k; i++)
		C[i] = C[i] + C[i-1];
	for(j = n; j >= 1; j--)
	{
		B[C[A[j]]] = A[j];
		C[A[j]] = C[A[j]] - 1;
	}

	FILE *fp;
	fp = fopen (nomeArquivo, "w");
	if (fp == NULL) {
		printf ("Houve um erro ao abrir o arquivo.\n");
		return ;
	}

	for(i = 1; i <= n; i++)
		fprintf(fp,"%i ", B[i]);
	fclose (fp);
}

int main(int argc,char *argv[]){

	int k = 0, count= 0;
	int * numbers = NULL;
	int * more_numbers;
	int numeroArquivo = 0;
	FILE *fp;
	int i;
	fp = fopen (argv[1], "r");

	while(fscanf(fp,"%d", &numeroArquivo) != EOF){
		if (numeroArquivo != '\0' && numeroArquivo != EOF) {
			count++;
			more_numbers = (int*) realloc (numbers, count * sizeof(int));
			if (more_numbers!=NULL) {
				numbers=more_numbers;
				numbers[count-1]=numeroArquivo;
			}
			else {
				free (numbers);
				puts ("Error (re)allocating memory");
				exit (1);
			}
			if(numeroArquivo > k){
				k = numeroArquivo;
			}
		}
	}
	fclose (fp);
	int vetB[count];
	int vetC[k];
	for (i = 0; i < k; ++i) {
			vetC[i] = 0;
		}
	for (i = 0; i < count; ++i) {
		vetB[i] = 0;
	}
	coutingSort(numbers, count, vetB, vetC, k);
	//Counting_sort(numbers, k, count, argv[2]);

	fp = fopen (argv[2], "w");
	if (fp == NULL) {
	}
	else {
		for(i = 0; i < count; i++)
			fprintf(fp,"%i ", numbers[i]);
		fclose (fp);

	}

	free(numbers);
	return 0;
}
